<?php

namespace app\sys\api;

use app\common\logic\AuthGroupAccess;
use app\common\logic\Menu;

class AuthGroup extends Common
{
    private $_authGroup = null;

    protected function m()
    {
        if ($this->_authGroup == null)
            $this->_authGroup = new \app\common\logic\AuthGroup();

        return $this->_authGroup;
    }

    public function add()
    {
        if (!$this->checkAuth())
            return $this->_error;

        $req = input('');
        $AuthGroup = new \app\common\logic\AuthGroup();

        //生成hashid
        $id = get_hashid();
        if ($id === false)
            return $this->error('出现内部错误，请稍后重试');

        $req['id'] = $id;

        $ret = $AuthGroup->addItem($req);
        if ($ret === false)
            return $this->error($AuthGroup->getError());

        return $this->success('添加成功');
    }

    public function update()
    {
        if (!$this->checkAuth())
            return $this->_error;

        $req = input('');

        if (!isset($req['id']) || empty($req['id']))
            return $this->error('请选择要更新的权限组');

        $id = $req['id'];

        if (isset($req['rules']) && !empty($req['rules'])) {
            $req['rules'] = $this->parse_rule($req['rules']);
        }

        $AuthGroup = new \app\common\logic\AuthGroup();
        $ret = $AuthGroup->updateItem($req, ['id' => $id]);
        if ($ret === false)
            return $this->error($AuthGroup->getError());

        return $this->success('更新成功');
    }

    private function parse_rule($rule)
    {
        $menu = Menu::where([])->order('sort')->select();

        $child = [];

        foreach ($menu as $k => $val) {
            $pid = $val['pid'];

            if (!empty($pid))
                $child[$pid][] = $val['id'];
        }

        foreach ($child as $k => $val) {
            if (empty($val)) continue;
            $same = array_values(array_intersect($val, $rule));
            $is_set = array_search($k, $rule);

            if ($is_set === false && !empty($same))
                $rule[] = $k;
        }

        foreach ($child as $k => $val) {
            if (empty($val)) continue;
            $same = array_values(array_intersect($val, $rule));
            $is_set = array_search($k, $rule);

            if ($is_set === false && !empty($same))
                $rule[] = $k;
        }

        return array_values(array_unique($rule));
    }

    /**
     * 删除
     * @return array|string
     * @author wb <pithyone@vip.qq.com>
     */
    public function delete()
    {
        if (!$this->checkAuth())
            return $this->_error;

        $req = input('');

        if (!isset($req['id']) || empty($req['id']))
            return $this->error('请选择要删除的权限组');

        $id = $req['id'];
        $ids = is_array($id) ? $id : [$id];

        $error = 0;
        $del_id = [];
        foreach ($ids as $val) {
            $ret_auth_group_access = AuthGroupAccess::get(['group_id' => $val]);

            if (!empty($ret_auth_group_access)) $error++;
            else $del_id[] = $val;
        }

        $ret = \app\common\logic\AuthGroup::destroy($del_id);

        if ($error > 0)
            return $this->error('选择的权限组中有用户存在，请删除用户后重试');

        if ($ret === false)
            return $this->error($this->m()->getError());
        else
            return $this->success('删除成功');
    }

    public function get()
    {
        if (!$this->checkAuth())
            return $this->_error;

        $req = input('');

        if (!isset($req['id']) || empty($req['id']))
            return $this->error('请选择要查看的权限组');

        $ret = \app\common\logic\AuthGroup::get($req['id']);
        if (!empty($ret))
            return $this->success($ret);
        else
            return $this->error('权限组不存在');
    }

    public function lists()
    {
        if (!$this->checkAuth())
            return $this->_error;

        $ret = \app\common\logic\AuthGroup::getList([], 'id,title,desc,create_time');
        return $this->success($ret);
    }

    public function menu_lists()
    {
        if (!$this->checkAuth())
            return $this->_error;

        $req = input('');

        if (!isset($req['id']) || empty($req['id']))
            return $this->error('请选择要更新的权限组');

        $group_id = $req['id'];

        $AuthGroup = \app\common\logic\AuthGroup::get(['id' => $group_id]);
        $rules = $AuthGroup['rules'];

        $menu = Menu::where([])->field('id,pid,title,desc,url,icon')->order('sort')->select();

        $temp = [];
        $ret = [];

        foreach ($menu as $key => $val) {
            $temp[$val['id']] = &$menu[$key];
            $menu[$key] = $val->toArray();

            if (!empty($rules) && in_array($val['id'], $rules))
                $menu[$key]['selected'] = 'selected';
        }

        foreach ($temp as $key => $val) {
            if ($val['pid'] == '') $ret[] = &$temp[$key];
            else $temp[$val['pid']]['child'][] = &$temp[$key];
        }

        return $this->success($ret);
    }
}